<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <template>
        <el-tabs @tab-click="switchTab">
          <el-tab-pane label="信息管理" name="userManager"/>
          <el-tab-pane label="密码管理" name="passwordManager"/>
        </el-tabs>
      </template>
      <el-row v-show="switchStatus==='userManager'">
        <el-col :span="12">
          <div class="grid-content bg-purple">
              <el-form
                ref="ruleForm2"
                :model="ruleForm2"
                :rules="rules2"
                label-width="100px"
                class="demo-ruleForm">
                <el-form-item v-if="belongToLine==0"
                  label="所属线路">
                  <el-select v-model="lineCode" placeholder="线路" clearable filterable style="width:100%" disabled>
                    <el-option
                      v-for="(item,index) in lineCodes"
                      :key="index"
                      :label="item.name"
                      :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="belongToLine==0"
                  label="所属车站">
                  <el-select v-model="stationCode" placeholder="车站" clearable filterable style="width:100%" disabled>
                    <el-option
                      v-for="(item,index) in stationCodes"
                      :key="index"
                      :label="item.name"
                      :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="角色">
                  <el-select v-model="rolesOption" placeholder="角色" clearable filterable style="width:100%" disabled>
                    <el-option
                      v-for="(item,index) in rolesOptions"
                      :key="index"
                      :label="item.roleName"
                      :value="item.roleId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="用户名"
                  prop="username">
                  <el-input
                    v-model="ruleForm2.username"
                    type="text"
                    disabled/>
                </el-form-item>
                <!-- <el-form-item label="手机号" prop="phone">
                  <el-input v-model="ruleForm2.phone" placeholder="验证码登录使用"/>
                </el-form-item>
                <el-form-item label="头像">
                  <el-upload
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    class="avatar-uploader"
                    action="/admin/sys-file/upload">
                    <img v-if="ruleForm2.avatar" id="avatar" :src="avatarUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"/>
                  </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitForm2('ruleForm2')">提交
                  </el-button>
                  <el-button @click="resetForm('ruleForm2')">重置</el-button>
                </el-form-item> -->
		 <el-form-item v-if="belongToLine==0"
                  label="其他账户信息">
		  <el-input v-model="strPersonOtherStation" style="width:700px"/>
                </el-form-item>
              </el-form>
          </div>
        </el-col>
      </el-row>
      <el-row v-show="switchStatus==='passwordManager'">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form
              ref="ruleForm"
              :model="ruleForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm">
              <el-form-item
                label="原密码"
                prop="password">
                <el-input
                  v-model="ruleForm.password"
                  type="password"
                  auto-complete="off"/>
              </el-form-item>
              <el-form-item
                label="新密码"
                prop="newpassword1">
                <el-input
                  v-model="ruleForm.newpassword1"
                  type="password"
                  auto-complete="off"/>
              </el-form-item>
              <el-form-item
                label="确认密码"
                prop="confirmPassword">
                <el-input
                  v-model="ruleForm.confirmPassword"
                  type="password"
                  auto-complete="off"/>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm('ruleForm')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
   </basic-container>
  </div>
</template>

<script>
import { handleImg, openWindow,obj2string } from '@/util/util'
import { mapState } from 'vuex'
import store from '@/store'
import { getStore } from '@/util/store'
import request from '@/router/axios'
import {getLineLists,getStationLists,getPersonOtherStation} from "@/api/subwayRat/reportMondify/reportMistakeInfo";
import {deptRoleList} from '@/api/admin/role'

export default {
  data() {
      var validatePass1 = (rule, value, callback) =>{
      if (value === '') {
        callback(new Error('请输入原密码'));
      } else {
        if (this.ruleForm.newpassword1 !== '') {
          this.$refs.ruleForm.validateField('newpassword1');
        }
        callback();
      }
    }
    var validatePass2 = (rule, value, callback) =>{
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {         
	 let  acount = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[!#@*&.])[a-zA-Z\d!#@*&.]*$/;		
	
	if (value && (!(acount).test(value))) {
	      callback(new Error('密码必须同时包含字母大写、小写、数字和特殊字符组成且至少8位'));
	 }else{
		   if (this.ruleForm.confirmPassword !== '') {
		  this.$refs.ruleForm.validateField('confirmPassword');
	         }	
	    callback();
	 }
	 
	
      }
    }
    var validatePass3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if (value !== this.ruleForm.newpassword1) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    return {
      switchStatus: 'userManager',
      avatarUrl: '',
      show: false,
      headers: {
        'Authorization': 'Bearer ' + store.getters.access_token,
      },
      ruleForm2: {
        username: '',
        avatar: '',
        phone: ''
      },
      ruleForm: {
        username: '',
        password: '',
        newpassword1: '',
        confirmPassword: ''
      },
      lineCode: {},
      stationCode: {},
      rolesOption: {},
      lineCodes: [],
      stationCodes: [],
      rolesOptions: [],
      personOtherStation:[],
      strPersonOtherStation:'',
      rules: {
        password: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 8, max: 20, message: '密码长度在 8 到 20 个字符', trigger: 'change' },
          { validator: validatePass1, trigger: 'blur' }
        ],
        newpassword1: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, max: 20, message: '密码长度在 8 到 20个字符', trigger: 'change' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'change' },
          { validator: validatePass3, trigger: 'blur' }
        ]
      },
      rules2: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {pattern: /^1[3-9]\d{9}$/,message: '手机号格式错误'}
        ]
      }
    }
  },
  created() {
      this.resetForm();
      this.initLine();
      this.initStation();
      this.getRoleList();
      this.initPersonOtherStation();
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      userRoles: state => state.user.roles
    })
  },
  methods: {
    switchTab(tab) {
      if (tab.name === 'userManager') {
        handleImg(this.ruleForm2.avatar, 'avatar');
        this.$refs.ruleForm2.resetFields();
      }
      this.switchStatus = tab.name
    },
    submitForm2(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.validatenull(this.ruleForm2.avatar)){
            this.$message.info("请选择头像");
            return; 
          }
          request({
            url: '/admin/user/edit',
            method: 'put',
            data: this.ruleForm2
          }).then(response => {
            if (response.data.data) {
              this.$notify.success('修改成功')
            } else {
              this.$notify.error(response.data.msg)
            }
          }).catch(() => {
            this.$notify.error('修改失败')
          })
        } else {
          return false
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            url: '/admin/user/edit',
            method: 'put',
            data: this.ruleForm
          }).then(response => {
            if (response.data.data) {
              this.$notify.success('修改成功')
              // 修改密码之后强制重新登录
              if (this.switchStatus === 'passwordManager') {
                this.$store.dispatch('LogOut').then(() => {
                  location.reload() // 为了重新实例化vue-router对象 避免bug
                })
              }
            } else {
              this.$notify.error(response.data.msg)
            }
          }).catch(() => {
            this.$notify.error('修改失败')
          })
        } else {
          return false
        }
      })
    },
    // resetForm(formName) {
    //   this.$nextTick(function() {
    //     this.$refs[formName].resetFields();
    //   })
    //   this.lineCode = this.userInfo.lineCode
    //   this.stationCode = this.userInfo.stationCode
    //   this.belongToLine = this.userInfo.belongToLine
    //   this.rolesOption = this.userRoles[0]
    //   this.ruleForm2.username = this.userInfo.username
    //   this.ruleForm2.phone = this.userInfo.phone
    //   this.ruleForm2.avatar = this.userInfo.avatar
    //   handleImg(this.userInfo.avatar, 'avatar')
    //   //判断是否选择了租户ID
    //   const TENANT_ID = getStore({ name: 'tenantId' })
    //   if (TENANT_ID) {
    //       this.headers['TENANT-ID'] = TENANT_ID // 租户ID
    //   }
    // },
    resetForm(formName) {
      this.ruleForm.password = undefined
      this.ruleForm.newpassword1 = undefined
      this.ruleForm.confirmPassword = undefined
      this.lineCode = this.userInfo.lineCode
      this.stationCode = this.userInfo.stationCode
      this.belongToLine = this.userInfo.belongToLine
      this.rolesOption = this.userRoles[0]
      this.ruleForm.username = this.userInfo.username
      this.ruleForm2.username = this.userInfo.username
      this.ruleForm2.phone = this.userInfo.phone
      this.ruleForm2.avatar = this.userInfo.avatar
      handleImg(this.userInfo.avatar, 'avatar')
      //判断是否选择了租户ID
      const TENANT_ID = getStore({ name: 'tenantId' })
      if (TENANT_ID) {
          this.headers['TENANT-ID'] = TENANT_ID // 租户ID
      }
    },
    handleAvatarSuccess(res, file) {
      this.avatarUrl = URL.createObjectURL(file.raw)
      this.ruleForm2.avatar = res.data.bucketName + '-' + res.data.fileName
    },
    initLine(){     
      let p={};     
      p.userCode=this.$store.getters.userInfo.userCode;
      getLineLists(p).then((res)=>{        
        this.lineCodes=res.data.data;
      });
      //alert("获取查询条件----"+JSON.stringify(this.lineCodes));

    },
    initStation(){
      let p={};
      p.userCode=this.$store.getters.userInfo.userCode;
      p.lineCode=this.$store.getters.userInfo.lineCode;
      getStationLists(p).then((res)=>{       
        this.stationCodes=res.data.data;
      })
    },
    initPersonOtherStation(){
       let p={};
       p.userCode=this.$store.getters.userInfo.userCode;       
       getPersonOtherStation(p).then((res)=>{       
        this.personOtherStation=res.data.data;
	if(this.personOtherStation!=null && this.personOtherStation.length>0){
	   let message = '';	  
	   for(let key of this.personOtherStation){
	      let disLineName = key.lineCode;
	      let disStationCode = key.stationCode;
	      message = message + " [工号："+key.userCode;
	      if(disLineName!=null && disLineName!=''){
	        message = message + "  线路："+disLineName;
	      }
	      if(disStationCode!=null && disStationCode!=''){
	        message = message + "  车站："+ disStationCode;
	      }
	      message = message + "] "
	      //message = message + " 工号："+key.userCode+" 线路："+key.lineCode+" 车站："+key.stationCode +";"
	   }
	   this.strPersonOtherStation = message;
	
	}
       })
    },
    getRoleList(){
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data;
      })
    },
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px !important;
    color: #8c939d !important;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center !important;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
